# ----------------------------------------------------------------------------
#       Copyright (C) 2013-2014 Huynh Vi Lam  <domovilam@gmail.com>
#
#       This file is part of pimucha.
#
#	This program is free software: you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation, either version 3 of the License, or
#	(at your option) any later version.
#	
#	This program is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#	
#	You should have received a copy of the GNU General Public License
#	along with this program.  If not, see <http://www.gnu.org/licenses/>.
# ----------------------------------------------------------------------------



# ----------------------------------------------------------------------------
# Script for communicate with controllers
# direct access to FTDI USB interface
# Require python-ftdi and libfti1 from www.intra2net.com
# Python version 2.7.x only
# ----------------------------------------------------------------------------
# python-ftdi
# -----------
# - Website: http://www.intra2net.com
# - Documentation and source code python-ftdi is used as base for development
# ----------------------------------------------------------------------------


import ftdi1 as ftdi
import logging

logger = logging.getLogger()


def vidpid(vid):
    try:
         p = vid.split(':')
         a = (int(p[0],16), int(p[1],16))
         return a
    except:
         return None


def finddevice(vid=None):
    # initialize
    ftdic = ftdi.new()
    if ftdic == 0:
        print('FTDI failed to initialise')
    # try to list ftdi devices
    if vid:
        vendorId, productId = vidpid(vid)
    else:
        vendorId, productId = 0x0403, 0x6001
    ret, devlist = ftdi.usb_find_all(ftdic, vendorId, productId)
    if ret < 0:
        print('ftdi_usb_find_all failed: %d (%s)' % (ret, ftdi.get_error_string(ftdic)))
    print('Number devices: %d' % ret)
    i = 0
    while(devlist != None):
        ret, manufacturer, description, serial = ftdi.usb_get_strings(ftdic, devlist.dev)
        if ret < 0:
            print('ftdi_usb_get_strings failed: %d (%s)' %
                 (ret, ftdi.get_error_string(ftdic)))
            print('Please, check permissions')
        print('#%d: manufacturer="%s" description="%s" serial="%s"\n' %
            (i, manufacturer, description, serial))
        devlist = devlist.next
        i += 1
    if i == 1 :
        return i, vendorId, productId
    else:
        return None
    ftdi.free(ftdic)
